package com.zha.service.impl;


import com.zha.constant.AuthConstants;
import com.zha.factory.LoginStrategyFactory;
import com.zha.strategy.LoginStrategy;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Title: 只有光头才能变强
 * @Author: 炸炸
 * @Date: 2024/12/7 18:09
 * 系统自己的认证流程
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从约定好的位置,即请求头中获取登录类型LoginType
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);
        // 判断LoginType是否有值
        if (!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录,登录类型不匹配");
        }
        // 根据登录类型,从登录策略工厂中生成指定登录类型的具体策略
        LoginStrategy instance = loginStrategyFactory.getInstance(loginType);
        return instance.realLogin(username);
    }
}
